//
// PPAssetsPickerViewController.m
// PPAssetsPickerViewController
//
// Created by Jinxiao on 9/13/16.
// Copyright © 2016 MicroDream. All rights reserved.
//

#import "PPAssetsPickerViewController.h"
#import "PPAssetsPictureViewController.h"
#import "PPAlbumContentViewController.h"

#import "PPAssetsGroupPickerView.h"
#import "PPAlbumEditContentViewController.h"
@import AssetsLibrary;

@interface PPAssetsPickerViewController () <PPAssetsGroupPickerViewDelegate, PPAssetsPickerViewCellDelegate, PPCameraViewControllerDelegate, PPAssetsPictureViewControllerDelegate>
@property (readwrite, nonatomic, strong) ALAssetsFilter *assetsFilter;
@property (readwrite, nonatomic, strong) ALAssetsLibrary *assetsLibrary;
@property (readwrite, nonatomic, strong) NSMutableArray <ALAssetsGroup *> *groups;
@property (readwrite, nonatomic, strong) UIButton *titleButton;
@property (readwrite, nonatomic, strong) UICollectionView *collectionView;
@property (readwrite, nonatomic, strong) DGPopoverView *groupPopoverView;

@property (readwrite, nonatomic, strong) NSMutableArray <ALAsset *> *selectedAssets;
@property (readwrite, nonatomic, strong) NSArray <ALAsset *> *assets;
@end

@implementation PPAssetsPickerViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.automaticallyAdjustsScrollViewInsets = YES;
    self.edgesForExtendedLayout = UIRectEdgeTop;
    self.view.backgroundColor = [UIColor whiteColor];

    _assetsLibrary = [[ALAssetsLibrary alloc] init];

    _assetsFilter = [ALAssetsFilter allPhotos];

    _groups = [[NSMutableArray alloc] init];
    _selectedAssets = [[NSMutableArray alloc] init];

    _titleButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _titleButton.titleLabel.font = [UIFont systemFontOfSize:17];
    [_titleButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_titleButton addTarget:self action:@selector(titleButtonDidPressed) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.titleView = _titleButton;

    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;

    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    [_collectionView registerClass:[PPAssetsPickerViewCell class] forCellWithReuseIdentifier:@"cell"];
    [_collectionView registerClass:[PPAssetsPickerViewCaptureCell class] forCellWithReuseIdentifier:@"captureCell"];
    _collectionView.backgroundColor = [UIColor clearColor];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.alwaysBounceVertical = YES;
    [self.view addSubview:_collectionView];

    [self reloadGroupsWithCompletion:^(NSError *error) {

        __block ALAssetsGroup *group = nil;

        [_groups enumerateObjectsUsingBlock:^(ALAssetsGroup *_Nonnull obj, NSUInteger idx, BOOL *_Nonnull stop) {
            if([[obj valueForProperty:ALAssetsGroupPropertyType] integerValue] == ALAssetsGroupSavedPhotos) {
                group = obj;
                *stop = YES;
            }
        }];

        if(group == nil) {
            group = _groups.firstObject;
        }

        [self reloadPhotosWithGroup:group];

    }];

    __weak typeof(self)weakSelf = self;
    [self setNavigationLeftTitle:@"取消" titleColor:[UIColor colorWithRGBHex:0xf2f2f2] action:^{
        [weakSelf.delegate assetsPickerViewControllerDidPressCancel:weakSelf];
    }];

    [self setNavigationRightTitle:@"确定" titleColor:[UIColor colorWithRGBHex:0xb2b2b2] action:^{
        if ([weakSelf.groups count] > 10)
        {
            [MobClick event:@"50"];
        }
        else
        {
            [MobClick event:@"49"];
        }
        [weakSelf.delegate assetsPickerViewControllerDidPressConfirm:weakSelf];
    }];

    [self selectedItemsDidChanged];
}

- (void)reloadGroupsWithCompletion:(void (^)(NSError *))completion {

    [_assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop) {

        if(group != nil) {
            [group setAssetsFilter:_assetsFilter];
            [_groups addObject:group];
        } else {
            !completion ? : completion(nil);
        }
    } failureBlock:^(NSError *error) {

        !completion ? : completion(error);
    }];

}

- (void)reloadPhotosWithGroup:(ALAssetsGroup *)group {

    [_titleButton setTitle:[group valueForProperty:ALAssetsGroupPropertyName] forState:UIControlStateNormal];
    [_titleButton sizeToFit];

    NSMutableArray <ALAsset *> *assets = [NSMutableArray array];

    [group enumerateAssetsWithOptions:NSEnumerationReverse usingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
        [assets addSafeObject:result];
    }];

    _assets = assets;
    [_selectedAssets removeAllObjects];

    [_collectionView reloadData];
}


- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];

    _collectionView.frame = self.view.bounds;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat width = (collectionView.width - 6)/4;

    return CGSizeMake(width, width);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 2;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 2;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if(!_hideCamera) {
        if(indexPath.row == 0) {
            PPAssetsPickerViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"captureCell" forIndexPath:indexPath];

            return cell;
        } else {
            PPAssetsPickerViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];

            ALAsset *asset = [_assets safeObjectAtIndex:indexPath.row - 1];

            cell.asset = asset;
            cell.delegate = self;
            cell.selectButton.selected = [_selectedAssets containsObject:asset];

            return cell;
        }
    } else {
        PPAssetsPickerViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];

        ALAsset *asset = [_assets safeObjectAtIndex:indexPath.row];

        cell.asset = asset;
        cell.delegate = self;
        cell.selectButton.selected = [_selectedAssets containsObject:asset];

        return cell;
    }
}

- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    if([cell isKindOfClass:[PPAssetsPickerViewCaptureCell class]]) {
        [((PPAssetsPickerViewCaptureCell *)cell) startCapture];
    }
}

- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    if([cell isKindOfClass:[PPAssetsPickerViewCaptureCell class]]) {
        [((PPAssetsPickerViewCaptureCell *)cell) stopCapture];
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if(!_hideCamera && indexPath.row == 0) {
        [MobClick event:@"51"];
        PPCameraViewController *cameraViewController = [[PPCameraViewController alloc] init];
        cameraViewController.cameraDelegate = self;
        [self presentViewController:cameraViewController animated:YES completion:nil];
    } else {
        PPAssetsPictureViewController *pictureViewController = [[PPAssetsPictureViewController alloc] init];

        NSMutableArray *artworks = [NSMutableArray array];

        for(ALAsset *asset in self.assets) {
            PPAbstractArtwork *artwork = [[PPAbstractArtwork alloc] init];
            artwork.asset = asset;
            [artworks addObject:artwork];
        }

        NSInteger index = indexPath.row;

        if(!_hideCamera) {
            index--;
        }

        pictureViewController.index = index;
        pictureViewController.artworks = artworks;
        pictureViewController.delegate = self;

        [self.navigationController pushViewController:pictureViewController animated:YES];
    }
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if(!_hideCamera) {
        return _assets.count + 1;
    } else {
        return _assets.count;
    }
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (void)didChangeSelection:(BOOL)selection forAsset:(ALAsset *)asset {
    if(selection) {
        [_selectedAssets addObject:asset];
    } else {
        [_selectedAssets removeObject:asset];
    }

    [self selectedItemsDidChanged];
}

- (void)selectedItemsDidChanged {

    UIBarButtonItem *confirmItem = self.navigationItem.rightBarButtonItem;

    if(_selectedAssets.count == 0) {
        confirmItem.enabled = NO;
        confirmItem.tintColor = [UIColor colorWithRGBHex:0xb2b2b2];
    } else {
        confirmItem.enabled = YES;
        confirmItem.tintColor = [UIColor colorWithRGBHex:0xffdd17];
    }
}

- (void)titleButtonDidPressed {

    if(_groupPopoverView == nil) {
        PPAssetsGroupPickerView *pickerView = [[PPAssetsGroupPickerView alloc] init];
        pickerView.frame = CGRectMake(0, 64, self.view.width, self.view.height - 64);
        pickerView.groups = _groups;
        pickerView.delegate = self;

        _groupPopoverView = [[DGPopoverView alloc] initWithContainerView:self.view contentView:pickerView options:DGPopoverViewAnimationOptionDownward backgroundStyle:DGPopoverViewBackgroundStyleNone];
    }

    [_groupPopoverView toggleAnimated:YES completion:nil];
}

- (void)assetsGroupPickerView:(PPAssetsGroupPickerView *)assetsGroupPickerView didSelectAssetsGroup:(ALAssetsGroup *)group {
    [self reloadPhotosWithGroup:group];

    [_groupPopoverView dismissAnimated:YES completion:nil];
}

- (void)cameraViewControllerDidPressCancel:(PPCameraViewController *)cameraViewController {
    [cameraViewController dismissViewControllerAnimated:YES completion:nil];
}

- (void)cameraViewController:(PPCameraViewController *)cameraViewController didSelectImages:(NSArray<UIImage *> *)images {

    NSMutableArray *artworks = [NSMutableArray array];
    [images enumerateObjectsUsingBlock:^(UIImage * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        PPAbstractArtwork *artwork = [[PPAbstractArtwork alloc] init];
        artwork.image = obj;
        artwork.uuid = [NSString uuid];
        [artworks addObject:artwork];
    }];

    
        PPAlbumEditContentViewController *createViewController = [[PPAlbumEditContentViewController alloc] init];
        createViewController.type = PPAlbumContentViewControllerTypeCreate;
    
        [createViewController.dataSource.images addObjectsFromArray:artworks];
        [createViewController.dataSource.insertedImages addObjectsFromArray:artworks];
    
        [self.navigationController pushViewController:createViewController animated:NO];
    
        [cameraViewController dismissViewControllerAnimated:YES completion:nil];
    
    
    
    
//    PPAlbumContentViewController *createViewController = [[UIStoryboard storyboardWithName:@"Album" bundle:nil] instantiateViewControllerWithIdentifier:@"PPAlbumContentViewController"];
//    createViewController.type = PPAlbumContentViewControllerTypeCreate;
//
//    [createViewController.dataSource.images addObjectsFromArray:artworks];
//    [createViewController.dataSource.insertedImages addObjectsFromArray:artworks];
//
//    [self.navigationController pushViewController:createViewController animated:NO];
//
//    [cameraViewController dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - PPAssetsPickerViewCellDelegate

- (void)assetsPickerViewCell:(PPAssetsPickerViewCell *)assetsPickerViewCell didChangeSelection:(BOOL)selection forAsset:(ALAsset *)asset {
    assetsPickerViewCell.selectButton.selected = selection;

    [self didChangeSelection:selection forAsset:asset];
}

#pragma mark - PPAssetsPictureViewControllerDelegate

- (void)pictureViewController:(PPAssetsPictureViewController *)pictureViewController didChangeSelectionOfItemAtIndex:(NSInteger)index {
    NSArray <ALAsset *> *assets = [self valueForKey:@"assets"];

    ALAsset *asset = [assets safeObjectAtIndex:index];

    BOOL selected = [self.selectedAssets containsObject:asset];

    [self didChangeSelection:!selected forAsset:asset];

    UICollectionView *collectionView = [self valueForKey:@"collectionView"];
    [collectionView reloadData];
}

- (BOOL)pictureViewController:(PPAssetsPictureViewController *)pictureViewController selectionStatusForItemAtIndex:(NSInteger)index {
    NSArray <ALAsset *> *assets = [self valueForKey:@"assets"];

    ALAsset *asset = [assets safeObjectAtIndex:index];

    BOOL selected = [self.selectedAssets containsObject:asset];

    return selected;
}

- (NSInteger)numberOfSelectionsForPictureViewController:(PPAssetsPictureViewController *)pictureViewController {
    return self.selectedAssets.count;
}

- (void)pictureViewControllerDidConfirmed:(PPAssetsPictureViewController *)pictureViewController {
    [self.delegate assetsPickerViewControllerDidPressConfirm:self];
}

@end











@implementation PPAssetsPickerViewCell

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];

    _imageView = [[UIImageView alloc] init];
    _imageView.backgroundColor = [UIColor colorWithRGBHex:0xF2F2F2];
    _imageView.contentMode = UIViewContentModeScaleAspectFill;
    _imageView.clipsToBounds = YES;
    [self.contentView addSubview:_imageView];

    _selectButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _selectButton.adjustsImageWhenHighlighted = NO;
    _selectButton.contentEdgeInsets = UIEdgeInsetsMake(6, 6, 6, 6);
    [_selectButton setImage:[UIImage imageNamed:@"radio-white-44"] forState:UIControlStateNormal];
    [_selectButton setImage:[UIImage imageNamed:@"radio-yellow-44"] forState:UIControlStateHighlighted|UIControlStateSelected];
    [_selectButton setImage:[UIImage imageNamed:@"radio-yellow-44"] forState:UIControlStateSelected];
    [_selectButton sizeToFit];
    [_selectButton addTarget:self action:@selector(selectButtonDidPressed:) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:_selectButton];

    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];

    _imageView.frame = self.contentView.bounds;

    _selectButton.top = 0;
    _selectButton.right = self.contentView.width;
}

- (void)selectButtonDidPressed:(UIButton *)button {
    button.selected = !button.selected;

    [_delegate assetsPickerViewCell:self didChangeSelection:button.selected forAsset:_asset];
}

- (void)setAsset:(ALAsset *)asset {
    _asset = asset;

    _imageView.image = asset.thumbnailImage;
}

@end


@implementation PPAssetsPickerViewCaptureCell

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];

    for(AVCaptureDevice *device in [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo]) {
        if([device position] == AVCaptureDevicePositionBack) {
            _device = device;
            break;
        }
    }

    _input = [AVCaptureDeviceInput deviceInputWithDevice:_device error:nil];

    _output = [[AVCaptureMetadataOutput alloc] init];
    [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];

    _session = [[AVCaptureSession alloc] init];
    [_session setSessionPreset:AVCaptureSessionPresetHigh];

    if([_session canAddInput:_input]) {
        [_session addInput:_input];
    }

    if([_session canAddOutput:_output]) {
        [_session addOutput:_output];
    }

    _output.metadataObjectTypes = _output.availableMetadataObjectTypes;

    _preview = [AVCaptureVideoPreviewLayer layerWithSession:_session];
    _preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
    [self.layer insertSublayer:_preview atIndex:0];

    _blurView = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]];
    [self addSubview:_blurView];

    _logoView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon-nav-camera"]];
    [self addSubview:_logoView];

    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];

    _preview.frame = self.layer.bounds;

    _blurView.frame = self.bounds;

    _logoView.center = _blurView.center;
}

- (void)startCapture {
    [_session startRunning];
}

- (void)stopCapture {
    [_session stopRunning];
}

@end
